import os
import sys
from devices import devices
import sys 
import hashlib
import urllib 
import os
import subprocess 
import fnmatch
import re

def setup():
	global iThing
	def get_osx_version():
		global osx_version
		osx_version = subprocess.check_output(["sw_vers"])
		osx_version = float(*re.findall(r'(?:ProductVersion:.*)(10\.[0-9])', osx_version)) 
		if osx_version >= 10.6:
			return 1
		else:
			return 0

	def get_xcode_version():
		global xcode_version
		try:
			xcode_version = subprocess.check_output(["xcodebuild", "-version"])
			xcode_version = float(re.findall(r"[0-9]+\.?[0-9]*", str(xcode_version))[0])
			return 1
		except OSError:
			return 0

	def set_dev_folder():
		global dev_folder_loc
		if os.path.exists("/Applications/Xcode.app/Contents/Developer"): dev_folder_loc = "/Applications/Xcode.app/Contents/Developer"
		if os.path.exists(os.path.expanduser("~/Applications/Xcode.app/Contents/Developer")): dev_folder_loc = os.path.expanduser("~/Applications/Xcode.app/Contents/Developer")
		if os.path.exists("/Developer"):     # allows to set global variable to developer location and return 0 or 1 based on developer location being in the correct spot for iphone_data_protection tools
			dev_folder_loc = "/Developer" # actualy it's a symlink but whatever
			return 1
		else:
			return 0

	def get_sdk_version():
		global sdk_version	
		sdk_version = [re.sub(r'iPhoneOS(?P<ver>[0-9]+\.?[0-9]*\.?[0-9]*)\.sdk', '\g<ver>', str(x)) for x in os.listdir(dev_folder_loc + "/Platforms/iPhoneOS.platform/Developer/SDKs")]
		for version in sdk_version:
			if float(version) >= 4:
				return 1
		else:
			return 0

	def chk_ldid():
		if os.path.exists("/usr/bin/ldid"):
			return 1
		else:
			return 0 

	def chk_mercurial():
		try:
			os.system("hg > /dev/null")	
			return 1
		except:
			return 0

	def chk_osxfuse():
		if os.path.exists('/Library/Filesystems/osxfusefs.fs'): 
			return 1
		else: 
			return 0


	def get_py():
		global py_version
		x, y = sys.version_info[0:2]
		py_version = float(str(x) + '.' + str(y))
		if py_version == 2.6 or 2.7:
			return 1
		else: 
			return 0 


	def chk_M2Crypto():
		try:
			import M2Crypto
			return 1
		except ImportError: return 0

	def chk_construct():
		try:
			import construct
			return 1
		except ImportError: return 0 

	def chk_progressbar():
		try:
			import progressbar
			return 1
		except ImportError: return 0 

	def chk_setuptools():
		try:
			import setuptools
			return 1
		except ImportError: return 0 

	def chk_pyCrypto():
		try:
			import Crypto
			return 1
		except ImportError: return 0

	def chk_codesign():
		if os.path.exists('/usr/bin/codesign_allocate'):
			return 1
		else:
			return 0 

	def chk_img3fs():
		if os.path.exists('iphone-dataprotection/img3fs/img3fs'):
			return 1
		else:
			return 0

	def chk_redsn0w():
		if os.path.exists('redsn0w_mac_0.9.12b2'):
			return 1
		else: return 0

	def download(url, location):
		urllib.urlretrieve(url, location, reporthook=dlProgress)

	def dlProgress(count, blockSize, totalSize):
		percent = int(count*blockSize*100/totalSize)
		sys.stdout.write("\r%2d%%" % percent)
		sys.stdout.flush()

	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	#------------------------------------------------------^------------------------------------------------------|----------------------------------------------
	#------------------------------------------------------|--------------------------------------------Do-Stuff--|----------------------------------------------
	#---------------------------------------------------Check-Stuff-----------------------------------------------v----------------------------------------------
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	msg = []


	if get_osx_version():
		msg.append("Osx version " + str(osx_version) + " running")


	if get_xcode_version():
		msg.append("Xcode version " + str(xcode_version) + " installed")
	else:
		msg.append("You need to install Xcode through the App Store")

	
	
	if set_dev_folder():
		msg.append("'/Developer' folder exists")
	else: 
		os.system('sudo ln -s ' + dev_folder_loc + ' /') 

	
	
	if get_sdk_version(): 
		msg.append( "iOS SDK versions are:\n")
		for version in sdk_version: msg.append( version)

	
	
	if chk_ldid():
		msg.append( "Ldid installed")
	else:
		download('http://networkpx.googlecode.com/files/ldid', 'ldid')
		os.system('sudo mv ldid /usr/bin; sudo chmod +x /usr/bin')


#	if chk_mercurial():
#		msg.append( "Mercurial installed")
#	else:
#		if osx_version == 10.6: merc_info = ['http://mercurial.berkwood.com/binaries/Mercurial-2.3.1-py2.6-macosx10.6.zip', '6b2436fb6ca5612ba9e551bd132204467a6ee9e1']
#		if osx_version == 10.7: merc_info = ['http://mercurial.berkwood.com/binaries/Mercurial-2.3.1-py2.7-macosx10.7.zip', '83a2988cd9371214e5eb39a4a06db4946b979ea1']
#		if osx_version == 10.8: merc_info = ['http://mercurial.berkwood.com/binaries/Mercurial-2.3.1-py2.7-macosx10.8.zip', 'ef0c9b6ddb2aed0cd50e28ddd70a0ddac3a48677']
#
#		download(merc_info[0], 'Mercurial.zip')
#		
#		if hashlib.sha1(open('Mercurial.zip')) == merc_info[1]: # Uses 700 mb of memory... will fix later        
#
#			os.system('unzip Mercurial.zip; sudo installer -pkg Mercurial.mkpg -target /')

	
	
	if chk_osxfuse():
		msg.append( 'OSx Fuse is installed')
	else:
		os.system('curl -O -L https://github.com/downloads/osxfuse/osxfuse/OSXFUSE-2.3.4.dmg;hdiutil mount OSXFUSE-2.3.4.dmg;sudo installer -pkg /Volumes/FUSE\ for\ OS\ X/Install\ OSXFUSE\ 2.3.pkg -target /;hdiutil eject /Volumes/FUSE\ for\ OS\ X/F;')

	
	
	if get_py():
		msg.append( 'Python version in use is ' + str(py_version) + '.')

	
	
	if chk_M2Crypto():
		msg.append( 'M2crypto is Installed')
	else:
		os.system('sudo easy_install M2crypto')

	
	
	if chk_construct():
		msg.append( 'construct is installed')
	else:
		os.system('sudo easy_install construct')
	
	
	if chk_progressbar():
		msg.append( 'progressbar is installed')
	else:
		os.system('sudo easy_install progressbar')

	
	
	if chk_setuptools():
		msg.append( 'setuptools is installed')
	else:
		os.system('sudo easy_install setuptools')

	
	
	if chk_pyCrypto():
		msg.append( 'pyCrypto is installed')
	else:
		os.system("sudo ARCHFLAGS='-arch i386 -arch x86_64' easy_install pycrypto")


	
	
	if chk_codesign():
		msg.append( 'Unix tools installed correctly')
	else:
		if os.path.exists('/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate'):
			os.system('sudo ln -s /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate /usr/bin')
		else:
			msg.append('You need to install the Xcode unix tools, you can do this in Xcode    Xcode--->Prefrences--->Downloads---->Commandline tools----->Download\nPress enter when done\n')

	
	
	if chk_img3fs():
		msg.append( 'img3fs installed')
	else:
		os.system('make -C iphone-dataprotection/img3fs')
			



	if chk_redsn0w():
		msg.append( 'Redsn0w is installed')
	else:
		try:
			subprocess.check_call("curl -O -L https://sites.google.com/a/iphone-dev.com/files/home/redsn0w_mac_0.9.12b2.zip", shell=True)
		except CalledProcessError:
			msg.appen( 'Something went wrong with "curl -O -L https://sites.google.com/a/iphone-dev.com/files/home/redsn0w_mac_0.9.12b2.zip"\nMaybe your not connected to the internet?')

		subprocess.check_call("unzip redsn0w_mac_0.9.12b2.zip;cp redsn0w_mac_0.9.12b2/redsn0w.app/Contents/MacOS/Keys.plist .", shell=True)
			

	return msg
